//
//  TableShowBtnCell+Config.swift
//  CooperSwift
//
//  Created by 计海峰 on 2021/12/9.
//

import UIKit
import RxSwift
import WebKit

public extension TableShowBtnCell {
    
    // MARK: - bind前 执行
    func layoutViews() {  }
    
    // MARK: - bind后 执行
    func loadData() {
        /// 执行一些 需求操作
        guard let config = info as? TableShowBtnCellModel else { return }
        
        /// 执行一次配置   生成一个默认按钮
        if !config.isConfigDone {  _ = btn  }
        
        /// 根据model添加 未生成的 btn
        if let btnControls = config.model as? [ViewControlProtocol] {
            if btnControls.count - btns.count > 0 {
                let number = btnControls.count - btns.count
                for _ in 1...number {
                    _ = createBtn()
                }
            }
        }
        
        /// 数据装载
        guard let cellModel = self.info as? TableShowBtnCellModel else { return }
        if !cellModel.isConfigDone { /// 执行一次配置
            cellModel.isConfigDone = true
            cellModel.once(btns, cell: self)
        }
        cellModel.every(btns, cell: self)
    }
    
    // MARK: - 创建按钮
    func createBtn() -> UIButton {
        let btn = UIButton(type: .custom)
        btn.setTitle("", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 15)
        btn.backgroundColor = .random()
        btn.tag = 800 + btns.count
        btn.frame = CGRect.init(20, 64.0 * CGFloat(btns.count), Screen.width - 40, 44)
        btn.isHidden = true
        btn.addTarget(self, action: #selector(btnTap(_:)), for: .touchUpInside)
        btns.append(btn)
        contentView.addSubview(btn)
        return btn
    }
    
    // MARK: - 按钮点击
    @objc func btnTap(_ btn: UIButton) {
        guard let config = self.info as? TableShowBtnCellModel else { return }
        if let btnControl = config.model as? ViewControlProtocol {
            guard let method = btnControl.method else { return }
            config.post(method, info: btnControl)
        }
        if let btnControls = config.model as? [ViewControlProtocol] {
            let index = btn.tag - 800
            guard let method = btnControls[safe: index]?.method else { return }
            config.post(method, info: btnControls[index])
        }
    }
    
}
